package com.mt.restaurant.service.sale.impl;

import com.mt.restaurant.dao.sale.PaymentRecordDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.sale.PaymentRecord;
import com.mt.restaurant.service.sale.PaymentRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class PaymentRecordServiceBean extends BaseService implements PaymentRecordService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private PaymentRecordDao paymentRecordDao;

	@Resource
	private RedisTemplate<String, List<PaymentRecord>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询付款记录集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findPaymentRecords(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindPaymentRecords(pageDTO);
		List<PaymentRecord> paymentRecordDTOS = this.paymentRecordDao.findPaymentRecords(pageDTO);
		Long totalCount = this.paymentRecordDao.findPaymentRecordTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(paymentRecordDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部付款记录集合
	 *
	 */
	@Override
	public List<PaymentRecord> findAllPaymentRecords(){
		return this.paymentRecordDao.findAllPaymentRecords();
	}

	/**
	 * 查询所有付款记录集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<PaymentRecord> findAllPaymentRecordsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllPaymentRecordsWithIdName();
		return this.paymentRecordDao.findAllPaymentRecordsWithIdName();
	}

	/**
	 * 根据名称查询付款记录集合(只提取ID 和 Name)
	 *
	 * @param paymentRecordName 名称
	 */
	@Override
	public List<PaymentRecord> findPaymentRecordsWithIdNameByName(String paymentRecordName){
		//TODO:请在此校验参数的合法性
		this.validateFindPaymentRecordsWithIdNameByName(paymentRecordName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:PaymentRecord_where_paymentRecordName_" + paymentRecordName);
		List<PaymentRecord> paymentRecords = new ArrayList<>();
		if (keys.isEmpty()) {
		paymentRecords = this.paymentRecordDao.findPaymentRecordsWithIdNameByName(paymentRecordName);
		redisTemplate.opsForValue().set("searchData:PaymentRecord_where_paymentRecordName_" + paymentRecordName, paymentRecords, 30, TimeUnit.DAYS);
		} else {
		paymentRecords = redisTemplate.opsForValue().get("searchData:PaymentRecord_where_paymentRecordName_" + paymentRecordName);
		}
		return paymentRecords;
	}

	/**
	 * 根据ID查询指定的付款记录(只提取ID 和 Name)
	 *
	 * @param paymentRecordId Id
	 */
	@Override
	public PaymentRecord findPaymentRecordsWithIdNameById(Long paymentRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindPaymentRecordsWithIdNameById(paymentRecordId);
		return this.paymentRecordDao.findPaymentRecordsWithIdNameById(paymentRecordId);
	}

	/**
	 * 根据ID查询指定的付款记录
	 *
	 * @param paymentRecordId Id
	 */
	@Override
	public PaymentRecord findPaymentRecord(Long paymentRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindPaymentRecord(paymentRecordId);
		return this.paymentRecordDao.findPaymentRecord(paymentRecordId);
	}

	/**
	 * 根据ID查询指定的付款记录(包含外键)
	 *
	 * @param paymentRecordId Id
	 */
	@Override
	public PaymentRecord findPaymentRecordWithForeignName(Long paymentRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindPaymentRecordWithForeignName(paymentRecordId);
		return this.paymentRecordDao.findPaymentRecordWithForeignName(paymentRecordId);
	}

	/**
	 * 新增付款记录
	 *
	 * @param paymentRecord 实体对象
	 */
	@Override
	public PaymentRecord savePaymentRecord(PaymentRecord paymentRecord){
		//TODO:请在此校验参数的合法性
		this.validateSavePaymentRecord(paymentRecord);
		//TODO:填充公共参数
		this.setSavePulicColumns(paymentRecord);
		Long rows = this.paymentRecordDao.savePaymentRecord(paymentRecord);
		if(rows != 1)
		{
			String error = "新增保存付款记录出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return paymentRecord;
	}

	/**
	 * 更新付款记录
	 *
	 * @param paymentRecord 实体对象
	 */
	@Override
	public PaymentRecord updatePaymentRecord(PaymentRecord paymentRecord){
		//TODO:请在此校验参数的合法性
		this.validateUpdatePaymentRecord(paymentRecord);
		Long rows = this.paymentRecordDao.updatePaymentRecord(paymentRecord);
		if(rows != 1)
		{
			String error = "修改保存付款记录出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return paymentRecord;
	}

	/**
	 * 根据ID删除付款记录
	 *
	 * @param paymentRecordId ID
	 */
	@Override
	public void deletePaymentRecord(Long paymentRecordId){
		//TODO:请在此校验参数的合法性
		this.validateDeletePaymentRecord(paymentRecordId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(PaymentRecord.class, paymentRecordId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.paymentRecordDao.deletePaymentRecord(paymentRecordId);
		if(rows != 1){
			String error = "删除付款记录出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindPaymentRecords(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	private void validateFindPaymentRecordsWithIdNameByName(String paymentRecordName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}


	private void validateFindAllPaymentRecordsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	private void validateFindPaymentRecordsWithIdNameById(Long paymentRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	private void validateFindPaymentRecord(Long paymentRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	private void validateFindPaymentRecordWithForeignName(Long paymentRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	private void validateSavePaymentRecord(PaymentRecord paymentRecord) {
	//不为空判断
	if (paymentRecord.getEid() != null || paymentRecord.getCreatorId() != null || paymentRecord.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	private void validateUpdatePaymentRecord(PaymentRecord paymentRecord) {
	//不为空判断
	if (paymentRecord.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.paymentRecordDao.findPaymentRecordTotalCount(PageDTO.create(PaymentRecord.FIELD_ID, paymentRecord.getEid())) == 0) {
	throw new BusinessException("修改的付款记录 " + paymentRecord.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	private void validateDeletePaymentRecord(Long paymentRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdatePaymentRecord()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
